import React, { Component } from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Platform,
  ScrollView,
  Image,
  Alert,
  Linking,
  ActivityIndicator,
  FlatList,
  ImageBackground,
  Dimensions,
  ToastAndroid,
  BackHandler,
  AppState,
  Clipboard,
  BackAndroid,
  NativeModules
} from 'react-native'
import {Actions} from "react-native-router-flux";
import Icon from 'react-native-vector-icons/Ionicons'
import colors from './../../styles/colors'
import RNAlibcSdk from 'react-native-alibc-sdk'
import * as WeChat from 'react-native-wechat'
import SplashScreen from 'react-native-splash-screen'
import { Overlay, Label, Button, SegmentedBar, Toast, Carousel  } from 'teaset'
import { SafeAreaView } from 'react-navigation';
import _updateConfig from '../../../update.json'
import JPushModule from 'jpush-react-native'
const {appKey} = _updateConfig[Platform.OS];

const PARAMS = {
  pid: "mm_108042659_0_0",
  forceH5: false
};

const {
  height: deviceHeight,
  width: deviceWidth
} = Dimensions.get("window");

import {
  isFirstTime,
  isRolledBack,
  packageVersion,
  currentVersion,
  checkUpdate,
  downloadUpdate,
  switchVersion,
  switchVersionLater,
  markSuccess,
} from 'react-native-update';
import Toast2 from "react-native-easy-toast";



class IndexScene extends Component{

  constructor(props){
    super(props)
    this.state = {
      ready: false,
      firstCate: [],
      secondCate: [],
      catMore: false,
      catCurrentItem:0,
      dataSource:[],
      currentCat: 16,
      currentCatSort: 'sort',
      currentCatTitle: '',
      isScroll: false,
      registrationId: null,
      activityPicWidth: 0,
      activityPicHeight: 0,
    }


  }


  static customKey = null;


  componentDidMount(){

    //极光推送安卓
    if (Platform.OS === 'android') {
      JPushModule.initPush() //启动极光推送

      JPushModule.notifyJSDidLoad((resultCode) => {
        if (resultCode === 0) {
        }
      })
    }

    SplashScreen.hide(); //隐藏启动页push

    if(Platform.OS === 'ios'){
      JPushModule.setBadge(0, success => {}) //把苹果的消息标记清零
    }


    try {
      WeChat.registerApp('wx9773b34689e823ea');//从微信开放平台申请
    } catch (e) {
      console.error(e);
    }


    RNAlibcSdk.init(PARAMS.pid, PARAMS.forceH5, (err) => {
      if (!err)
        console.log("init taobao success")
      else
        console.log(err)
    });


    if (isFirstTime) {
      markSuccess()
    }

    //热更新
    this.checkUpdate();

    //获取分类
    this.props.actions.getGoodsCateTop()
    //获取活动列表
    this.props.actions.getActivityList({position:'index'})
    //获取系统配置信息
    this.props.actions.getSystemList()

    AppState.addEventListener('change', this._handleAppStateChange);


    //接受推送通知
    this.receiveNotificationListener = map => {
      console.log(map)
    }
    JPushModule.addReceiveNotificationListener(this.receiveNotificationListener)


    //点解推送通知
    this.openNotificationListener = map => {
      if(Platform.OS === 'ios'){
        JPushModule.setBadge(0, success => {}) //把苹果的消息标记清零
      }

      this.pushAction(map)
    }
    JPushModule.addReceiveOpenNotificationListener(this.openNotificationListener)
  }


  //推送跳转接口
  pushAction(map){
    if(map && map.extras){
      let pushData = map.extras
      if(Platform.OS === 'android'){
        pushData = JSON.parse(map.extras)
      }
      switch (pushData.jump.scene) {
        case 'price':
          Actions.UserPrice()
          break;
        case 'order':
          Actions.UserOrder()
          break;
        case 'user_share':
          Actions.UserShare()
          break;
      }
    }
  }



  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
    if (Platform.OS === 'android') {
      JPushModule.removeReceiveNotificationListener(this.receiveNotificationListener);
      JPushModule.removeReceiveOpenNotificationListener(this.openNotificationListener);
      console.log("Will clear all notifications");
      JPushModule.clearAllNotifications();
    }
  }

  //监听剪切板
  _handleAppStateChange = (nextAppState) => {
    if(nextAppState === 'active'){
      Clipboard.getString().then((content)=>{
        // console.log(content.length)
      if(content.indexOf(global.default_kouling) < 0){
        if(content.indexOf('寳') > 0 || content.length == 13){
          this.props.actions.getGoodsKey({
            keyword: content
          })
        }else {
          // console.log(2222)
        }
      }
      })
    }
  }


  componentWillReceiveProps(nextProps) {

    const {goodsCate, goodsList, goodsKey, goodsCateTop, activityList, systemList} = nextProps

    //系统配置信息
    if(this.props.systemList !== systemList){
      if(systemList.error !== false){
        if(systemList.error.status === 401){

        }

        this.toast.show(systemList.error.message)
      }else{
        if(systemList && systemList.data){
          if(systemList.data.data.default_kouling){
            global.default_kouling = systemList.data.data.default_kouling;
            Clipboard.setString(systemList.data.data.default_kouling);
          }
        }
      }
    }

    if(this.props.goodsCateTop !== nextProps.goodsCateTop){
      if(goodsCate.error){
        this.toast.show(goodsCate.error.message)
      }else{
        if (goodsCate.isLoading) {
          this.showCustom()
        }else{
          this.hideCustom()
          if(goodsCateTop.data && goodsCateTop.data.length > 0){
            this.props.actions.getGoodsCate({cid: goodsCateTop.data[0].id})
            this.setState({firstCate: goodsCateTop});
            this.firstCate = goodsCateTop;
          }
        }
      }
    }

    if(this.props.goodsCate !== nextProps.goodsCate){
      if(goodsCate.error){
        this.toast.show(goodsCate.error.message)
      }else{
        if (goodsCate.isLoading) {
          this.showCustom()
        }else{
          this.hideCustom()
          if(goodsCate.data && goodsCate.data.length > 0){
            this.setState({secondCate: goodsCate});
            if(goodsCate.data[0].cat == 1624){
              this.props.actions.getGoodsListIndex({
                page:1,
                cat: this.state.currentCat
              })
            }
          }
        }
      }
    }


    if(this.props.goodsList !== nextProps.goodsList){
      if(goodsList.error !== false){
        this.toast.show(goodsList.error.message)
      }else {

        if (goodsList.isLoading) {
          // TO-DO
        } else {
          if (goodsList.data.length > 0) {

            if (goodsList.page === 1) {
              this._setRows(goodsList.data);
            } else {
              this._setRows(this._getRows().concat(goodsList.data));
            }

            this.setState({
              dataSource: this._getRows(),
            });

            //console.log(goodsList.page)
            this._setPage(goodsList.page);
            this._setRowDataAll(false)
          }else{
            this._setRowDataAll(true)
          }
        }
      }
    }


    //口令搜索
    if(this.props.goodsKey !== goodsKey){
      if(goodsKey.error !== false){
        if(goodsKey.error.status === 401){

        }

        this.toast.show(goodsKey.error.message)
      }else{

        if (goodsKey.isLoading === true) {
          Toast.show({
            text: '正在识别',
            icon: <ActivityIndicator size='large' color='#fff'/>,
            position: 'center',
          });
        }else{
          Clipboard.setString(global.default_kouling);
          if (goodsKey.data.length > 0) {
          // console.log(Actions.currentScene)
            if(Actions.currentScene === 'taoBaoWeb'){
              Actions.refresh({...goodsKey.data[0], resultJifen:1, refresh: true})
            }else{
              Actions.taoBaoWeb({...goodsKey.data[0], resultJifen:1})
            }
            // console.log(goodsKey.data[0]);
            // Actions.taoBaoWeb({...goodsKey.data[0], resultJifen:1})

          }else{
            Clipboard.setString(global.default_kouling);
            Toast.info('该产品没有优惠了');
          }
        }
      }
    }


    //活动信息
    if(this.props.activityList !== activityList){
      if(activityList.error !== false){
        if(activityList.error.status === 401){

        }

        this.toast.show(activityList.error.message)
      }else{
        if(activityList && activityList.data.length > 0){
          Image.getSize("https://tao.vyxjj.com"+activityList.data[0].pic, function (width, height) {
            console.log(height)
            this.setState({activityPicHeight:height, activityPicWidth:width})
          }.bind(this))
        }
      }
    }





  }

  _show(url) { //活动跳转函数
    if(url.indexOf('m.tb.cn') !== -1){
      RNAlibcSdk.show({type: "url", payload:url}, (err, info) => {
          if (!err)
            console.log(info)
          else
            console.log(err)
        }
      );
    }else{
      Actions.webView({url:url, title:'活动详情'})
    }
  }

  showCustom(){
    if (IndexScene.customKey) return;
    IndexScene.customKey = Toast.show({
      text: '正在加载',
      icon: <ActivityIndicator size='large' color='#fff'/>,
      position: 'center',
    });
  }

  hideCustom() {
    if (!IndexScene.customKey) return;
    Toast.hide(IndexScene.customKey);
    IndexScene.customKey = null;
  }


  _setRows(rows) {
    this._rows = rows;
  }
  _getRows() {
    return this._rows ? this._rows : [];
  }

  _setPage(page) {
    this._page = page;
  }
  _getPage() {
    return this._page ? this._page : 0;
  }


  _setRowDataAll(rowDataAll) {
    this._rowDataAll = rowDataAll;
  }
  _getRowDataAll() {
    return this._rowDataAll ? this._rowDataAll : false;
  }

  doUpdate = info => {
    downloadUpdate(info).then(hash => {

      Overlay.show(this.renderUpdateView('下载完毕\n\n是否重启应用?', 'finish', hash))
    }).catch(err => {
      Alert.alert('提示', '更新失败');
    });
  };

  checkUpdate = () => {
    checkUpdate(appKey).then(info => {
      if (info.expired) {
        Overlay.show(this.renderUpdateView('版本已更新\n\n请前往应用商店下载新的版本', 'all', info))

      } else if (info.upToDate) {
        //Alert.alert('提示', '您的应用版本已是最新.');
      } else {


        Overlay.show(this.renderUpdateView('检查到新的版本\n'+info.name+',是否下载?\n\n'+ info.description, 'hot', info))
      }
    }).catch(err => {
      //Alert.alert('提示', '更新失败.');
    });
  };


  //改变分段器的item
  cateChange(props){
    this.props.actions.getGoodsCate({cid:this.props.goodsCateTop.data[props].id})
    this.setState({catCurrentItem: props, catMore:false, currentCat:this.props.goodsCateTop.data[props].cat, currentCatTitle:this.props.goodsCateTop.data[props].title})
    this._setPage(1)
    this.props.actions.getGoodsListIndex({
      page:1,
      cat: this.props.goodsCateTop.data[props].cat,
      keyword: this.props.goodsCateTop.data[props].title,
      sort: this.state.currentCatSort,
      startPrice: 10,
    })
    this.myFlatList.scrollToOffset({x: 0, y: 0, animated: true});
    // this.myFlatList.scrollToOffset({offset: 0, animated: true});
  }

  //点击第二分类item
  secondCateChange(data){
    console.log(data)
    this.setState({currentCat:data.cat, currentCatTitle:data.title})
    this._setPage(1)
    this.props.actions.getGoodsListIndex({
      page:1,
      cat: data.cat,
      keyword: data.title,
      sort: this.state.currentCatSort,
      startPrice: 10,
    })
    //this.myScrollView.scrollToEnd({animated: true})
    // this.myFlatList.scrollToOffset({offset: 0, animated: true});
  }

  //改变产品排序条件
  goodSortChange(props){
    let sort = 'sort';
    switch (props) {
      case 0 :
          sort = 'sort'
        break;
      case 1 :
          sort = 'hot'
        break;
      case 2 :
          sort = 'price'
        break;
    }
    this.setState({currentCatSort: sort})
    this._setPage(1)
    this.props.actions.getGoodsListIndex({
      page:1,
      cat: this.state.currentCat,
      keyword: this.state.currentCatTitle,
      sort: sort,
      startPrice: 10,
    })
    //this.myScrollView.scrollTo({x: 0, y: deviceHeight / 2.7, animated: true})
    //this.myFlatList.scrollToOffset({offset: 0, animated: true});
  }

  //展开更多
  moreButton(){
    this.setState({catMore:true})
    this.myFlatList.scrollToOffset({x: 0, y: 0, animated: true});
    //this.myFlatList.scrollToOffset({offset: 0, animated: true});
  }


  //下拉刷新
  onPullReleaseData(){
    if(Actions.currentScene === "_index"){
      this.props.actions.getGoodsListIndex({
        page: 1,
        cat: this.state.currentCat,
        sort: this.state.currentCatSort,
        keyword: this.state.currentCatTitle,
        startPrice: 10,
      })
    }

  }


  //下拉更多
  onEndReached(){
    if(Actions.currentScene === "_index"){
      this.props.actions.getGoodsListIndex({
        page: this._getPage() + 1,
        cat: this.state.currentCat,
        sort: this.state.currentCatSort,
        keyword: this.state.currentCatTitle,
        startPrice: 10,
      })
    }
  }




  renderUpdateView(text, type, info){
    return(
      <Overlay.PopView
        style={{alignItems: 'center', justifyContent: 'center'}}
        ref={v => this.customPopView = v}
        onDisappearCompleted={()=>{
          if(type === 'finish'){
            switchVersionLater(info)
          }
        }}
      >
        <View style={{backgroundColor: '#fff', minWidth: 230, minHeight: 180, borderRadius: 15, paddingVertical: 20, alignItems: 'center'}}>
          <Label type='title' size='lg' text='提示' />
          <View style={{marginHorizontal:15, alignItems:'center', marginVertical:20}}>
            <Label type='title' size='md' text={text} numberOfLines={10} style={{textAlign:'center'}}/>
          </View>
          <Button title='确定' onPress={() => {
            switch (type){
              case 'all':
                info.downloadUrl && Linking.openURL(info.downloadUrl)
                this.customPopView && this.customPopView.close()
                break;
              case 'hot':
                this.doUpdate(info);
                this.customPopView && this.customPopView.close()
                break;
              case 'finish':
                switchVersion(info)
                break;
            }


          }} style={{marginTop:10}} />
        </View>
      </Overlay.PopView>
    )
  }


  renderSearch(){ //搜索的布局样式
    return(
     <View style={{height:45, backgroundColor:'#E12F32', flexDirection:'row', alignItems:'center', paddingHorizontal:5}}>
      <Image source={{uri: 'https://tao.vyxjj.com/build/images/logo.png'}} style={{height:30, width:100}} resizeMode='contain'/>
       <View style={styles.searchContent}>
         <Icon name="ios-search" size={20} style={styles.searchIcon}/>
         <TouchableOpacity activeOpacity={1} style={{flex:1, justifyContent:'center'}} onPress={()=>{
           Actions.lists({searchModal:true})
         }}>
           <Text style={styles.searchText}>请输入商品名、口令、或链接</Text>
         </TouchableOpacity>
       </View>
     </View>
    )
  }


  renderCategory(){
    if(this.state.catMore){
      return(
        <View style={styles.cateContainer}>
          <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
            <Text>全部分类</Text>
          </View>
          <View style={styles.cateClose}>
            <TouchableOpacity activeOpacity={1} onPress={()=>{
              this.cateChange(this.state.catCurrentItem)
            }}>
              <Icon name="ios-close" size={36} color="#ccc"/>
            </TouchableOpacity>
          </View>
        </View>
      )
    }else{
      const {data, isLoading} = this.props.goodsCateTop;
      if(isLoading){
        return(
          <View style={{marginTop:10, justifyContent:'center', alignItems:'center'}}>
            <Text>正在刷新，请稍等...</Text>
          </View>
        )
      }else if(data && isLoading === false){
        return(
          <View style={styles.cateContainer}>
            <SegmentedBar
              justifyItem='scrollable'
              indicatorType='boxWidth'
              indicatorLineColor='#E12F32'
              onChange={(props)=>this.cateChange(props)}
              activeIndex={this.state.catCurrentItem}
              //style={styles.cateBar}
            >
              {data.map(function (e, i) {
                return(
                  <SegmentedBar.Item
                    title={e.title} key={i}
                    titleStyle={{color:'#5f5f5f', fontSize:15}}
                    activeTitleStyle={{color:'#E12F32', fontSize:15}}
                    style={{width:50}}
                  />
                )
              })}

            </SegmentedBar>
            <View style={styles.cateMore}>
              <TouchableOpacity activeOpacity={1} onPress={()=>{this.moreButton()}}>
                <Image source={require('./../../../assets/images/cat_more.png')} style={{width:15, height:15}}/>
              </TouchableOpacity>
            </View>
          </View>
        )
      }
    }
  }


  renderCateContent(){
    if(this.state.catMore){
      const {data, isLoading} = this.props.goodsCateTop;
      if(!data || isLoading){
        return(
          <View style={{height:30, justifyContent:'center', alignItems:'center'}}>
            <Text>正在刷新，请稍等...</Text>
          </View>
        )
      }else if(data && isLoading === false){
        return(
          <View style={styles.cateContent}>
            {data.map(function (e, i) {
              return(
                <TouchableOpacity activeOpacity={1} style={styles.cateItem} key={i} onPress={()=>{
                  this.cateChange(i)
                }}>
                  <Image source={{uri: e.pic}} style={{width:50, height:50, marginBottom:3}}/>
                  <Text numberOfLines={4} style={{fontSize:13}} >{e.title}</Text>
                </TouchableOpacity>
              )
            }.bind(this))}
          </View>
        )
      }
    }else{
      const {data, isLoading} = this.state.secondCate;

      if(!data || isLoading){
        return(
          <View style={{height:30, justifyContent:'center', alignItems:'center'}}>
            <Text>正在刷新，请稍等...</Text>
          </View>
        )
      }else if(data && isLoading === false){
        return(
          <View style={styles.cateContent}>
            {data.map(function (e, i) {
              return(
                <TouchableOpacity activeOpacity={1} style={styles.cateItem} key={i} onPress={()=>{
                  this.secondCateChange(e);
                }}>
                  <Image source={{uri: e.pic}} style={{width:50, height:50, marginBottom:3}}/>
                  <Text numberOfLines={4} style={{fontSize:13}}>{e.title}</Text>
                </TouchableOpacity>
              )
            }.bind(this))}
          </View>
        )
      }
    }
  }


  renderGoodSelectContent(){
    return(
      <SegmentedBar
        style={{marginTop:10, height:40}}
        indicatorType='boxWidth'
        indicatorLineColor='#fff'
        onChange={(props)=>this.goodSortChange(props)}
      >
        <SegmentedBar.Item
          title='综合'
          titleStyle={{color:'#5f5f5f', fontSize:15}}
          activeTitleStyle={{color:'#E12F32', fontSize:15}}
          style={{width:50}}
        />
        <SegmentedBar.Item
          title='销量'
          titleStyle={{color:'#5f5f5f', fontSize:15}}
          activeTitleStyle={{color:'#E12F32', fontSize:15}}
        />
        <SegmentedBar.Item
          title='价格'
          titleStyle={{color:'#5f5f5f', fontSize:15}}
          activeTitleStyle={{color:'#E12F32', fontSize:15}}
          style={{width:50}}
        />
      </SegmentedBar>
    )
  }


  renderItem(data){


    let incomeratio = data.item.tkRate ? data.item.tkRate : data.item.incomeratio
    let jifen = ((((data.item.zkPrice - data.item.couponAmount) * ((incomeratio / 100))) * (this.props.goodsList.return_one_price / 100)) * 10)
    jifen = jifen < 0 ? 0: jifen.toFixed(2)

    let VJifen = '', vjifen= ''
    if(this.props.goodsList.data.levelRatio){
      if(this.props.goodsList.data.levelRatio !== '0'){
        vjifen = jifen * (this.props.goodsList.data.levelRatio / 100)
        VJifen = '(V+'+vjifen.toFixed(2)+')'
      }
    }else{
      if(data.levelRatio){
        if(data.levelRatio !== '0'){
          vjifen = jifen * (data.levelRatio / 100)
          console.log(vjifen);
          VJifen = '(V+'+vjifen.toFixed(2)+')'
        }
      }
    }

    let resultJifen = jifen + VJifen //最终的积分



    let price = data.item.zkPrice - data.item.couponAmount;
    return(
      <TouchableOpacity activeOpacity={1} style={{flex:1, backgroundColor:'#fff', borderBottomLeftRadius:10, borderBottomRightRadius:10,
        marginRight: 8, marginTop:8
      }} onPress={()=>{
        Actions.taoBaoWeb({...data.item, resultJifen})
        // jdSkd.show("https://u.jd.com/ubdAP9")
      }}>
        {data.item.userType == 1  ?
          <Image source={require('./../../../assets/images/listtmall.png')} style={{position:"absolute", zIndex:99
          }}/>
          :  null
        }
        <Image source={{uri: data.item.pictUrl}} style={{height:180}}  defaultSource={require('./../../../assets/images/defaultImg.jpg')}/>

        <View style={{paddingHorizontal: 5, flex:1}}>
          <Text numberOfLines={2} ellipsizeMode='tail' style={styles.itemTitle}>
            <Text textAlign='justify' style={styles.postage} textAlignVertical='center'> 包邮 </Text> {data.item.title}
          </Text>

          <View style={{flexDirection:'row', alignItems:'center', justifyContent: 'space-between', marginBottom:4}}>
            <Text style={{color:'#acacac', fontSize:15, marginRight: 5, textDecorationLine: 'line-through'}}>¥{data.item.zkPrice}</Text>
            <ImageBackground style={{width:60, height:30, justifyContent:'center', alignItems:'center'}} resizeMode='contain' source={require('./../../../assets/images/quan.png')}>
              <Text style={{color:'#fff', fontSize:13}}>{data.item.couponAmount}元券</Text>
            </ImageBackground>
          </View>

          <View style={{flexDirection:'row', justifyContent:'space-between', alignItems:'center', marginBottom:3}}>
            <Text style={{color:'#EF422D', fontSize:13, fontWeight: '400'}}>到手 ¥ <Text style={{fontSize:18, fontWeight: 'bold'}}>{price.toFixed(2)}</Text></Text>
            <Text style={{color:'#acacac', fontSize:13}}>{data.item.biz30day}人付款</Text>
          </View>
          {data.item.yongjin != 0  ?
            <View style={{borderLeftColor:'#EF422D', borderLeftWidth:3, paddingLeft:2, marginBottom:5}}>
              <Text style={{color:'#EF422D', fontSize:13}}>预计收入:￥{data.item.yongjin}</Text>
            </View>
            :  null
          }
        </View>

      </TouchableOpacity>
    )
  }

  renderGoodContent(){
    return(
      <FlatList
        ref={(view) => { this.myFlatList = view; }}
        data={this.state.dataSource}
        renderItem={this.renderItem.bind(this)}
        numColumns={2}
        onEndReached={this.onEndReached.bind(this)}
        onEndReachedThreshold={0.8}
        ListHeaderComponent={this.ListHeaderComponent()}
        ListFooterComponent={this.ListFooterComponent.bind(this)}
        ListEmptyComponent={this.ListEmptyComponent.bind(this)}
        refreshing={this.props.goodsList.isLoading}
        onRefresh={this.onPullReleaseData.bind(this)}
        columnWrapperStyle={{marginLeft:8}}
        nestedScrollEnabled={true}
        onScroll={(e)=>{
          let offsetY = e.nativeEvent.contentOffset.y;
          if(offsetY > 400){
            this.setState({isScroll: true})
          }else{
            this.setState({isScroll: false})
          }
        }}
      />
    )
  }

  ListHeaderComponent(){
    return(
      <View>
        {this.renderActivity()}
        {this.renderCateContent()}
        {this.renderGoodSelectContent()}
      </View>
    )
  }

  ListEmptyComponent(){
    return(
      <View style={{height:30, justifyContent:'center', alignItems:'center'}}>
        <Text>正在刷新，请稍等...</Text>
      </View>
    )
  }

  ListFooterComponent(){
    if(this._getRowDataAll()){
      return (
        <View style={{height:30, justifyContent:'center', alignItems:'center'}}>
          <Text>已经到底了</Text>
        </View>
      );
    }else{
      return (
        <View style={{height:30, justifyContent:'center', alignItems:'center'}}>
          <Text>下拉加载更多</Text>
        </View>
      );
    }

  }


  renderActivity(){

    if(this.state.catMore == false){
      const {data} = this.props.activityList
      if(data.length > 0){
        return(
          <Carousel style={{height: this.state.activityPicHeight/ 1.7}}>
            {data.map(function (e, i) {
              return(
                <TouchableOpacity activeOpacity={1} style={{ flex:1, backgroundColor:'#fff'}} onPress={()=>{this._show(e.url)}} key={i}>
                  <Image source={{uri:'https://tao.vyxjj.com'+e.pic}} style={{flex: 1, height:this.state.activityPicHeight/ 1.7 }} resizeMode='stretch'/>
                </TouchableOpacity>
              )
            }.bind(this))}
          </Carousel>

        )
      }
    }

  }


  renderReturnTop(){
      return(
        <View>
          {this.state.isScroll ?
            <TouchableOpacity style={[styles.floatButton, {bottom: 100 ,right:20}]} onPress={()=>{
              this.myFlatList.scrollToOffset({x: 0, y: 0, animated: true});
            }}>
              <Image source={require('./../../../assets/images/top.png')} style={{width:50, height:50}}/>
            </TouchableOpacity> :
            null
          }

          <TouchableOpacity style={[styles.floatButton, {bottom: 50 ,right:20}]} onPress={()=>{Actions.jump('UserHistory', {refresh:true})}}>
            <Image source={require('./../../../assets/images/jiao.png')} style={{width:50, height:50}}/>
          </TouchableOpacity>
        </View>
      )
  }

  render(){
    return(
      <SafeAreaView style={styles.container}>
        <View style={styles.headerContainer}>
          {this.renderSearch()}
          {this.renderCategory(this.firstCate)}
        </View>
        {this.props.goodsList.isLoading && this._getPage() === 1 ? this.showCustom() : this.hideCustom()}
        {this.renderGoodContent()}
        {this.renderReturnTop()}

        <Toast2
          ref={view => this.toast = view}
          style={{backgroundColor:'red'}}
          opacity={0.6}
          position='top'/>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container:{
    //paddingTop: Platform.OS === 'ios' ? 20 : 0,
    // backgroundColor:'#fff',
    backgroundColor:'#F5F5F5',
    flex:1,
  },
  logoContainer:{
    justifyContent:'center',
    alignItems:'center',
    marginTop:30,
  },
  logo:{
    width:200,
    height:25
  },
  headerContainer:{
    height:85,
    backgroundColor:'#fff'
  },
  searchContainer:{
    marginTop:10,
    height:40,
    flexDirection:'row',
    marginBottom:10,
  },
  searchContent:{
    flex:1,
    backgroundColor:'#f6f6f6',
    flexDirection:'row',
    alignItems:'center',
    marginLeft:15,
    height:30
  },
  searchIcon:{
    marginLeft:10,
    color: '#000'
  },
  searchText:{
    color:'#000',
    marginLeft:5,
    fontSize:14,
  },
  priceContainer:{
    // backgroundColor:'#0f0',
    height:80,
  },
  line:{
    borderBottomColor:'#e8e8e8',
    borderBottomWidth:1.5,
    height:20,
  },
  lineText:{
    position:'absolute',
    top:10,
    backgroundColor:'#fff',
    left:140,
    color:'#000',
    fontSize:15
  },
  priceItem:{
    // backgroundColor:'#f00',
    marginTop:10,
    flex:1,
    justifyContent:'space-around',
    flexDirection:'row',
    alignItems:'center'
  },
  priceButton:{
    justifyContent:'center',
    alignItems:'center',
    width:70,
    height:30,
    position:'relative',
  },
  priceItemBg:{
    width:70,
    height:30,
  },
  priceItemText:{
    position:'absolute'
  },
  cateContainer:{
    flex:1,
    flexDirection:'row',
    borderBottomColor: '#e8e8e8',
    borderBottomWidth: 1,
    backgroundColor:'#fff'
  },
  cateBottom:{
    width:75,
    height:100,
    marginVertical:10,
    alignItems:'center'
  },
  cateImg:{
    width:75,
    height:80,
  },
  cateMore:{
    width:50,
    justifyContent:'center',
    alignItems:'center',
    backgroundColor:'#fff',
    borderLeftColor:'#e8e8e8',
    borderLeftWidth:1,
  },
  cateContent:{
    flexWrap:'wrap',
    flexDirection:'row',
    borderBottomColor:'#fff',
    borderBottomWidth:1,
    backgroundColor:'#fff',
    paddingLeft: 10
    // justifyContent:'center'
  },
  cateItem:{
    width:deviceWidth / 6,
    height:80,
    justifyContent:'center',
    alignItems:'center',
    margin:5,
  },
  cateClose:{
    width:50,
    justifyContent:'center',
    alignItems:'center',
    position:'absolute',
    right:0,
    top:2,
    borderLeftColor:'#e8e8e8',
    borderLeftWidth:1,
  },
  postage:{
    color:'#fff',
    backgroundColor:'#FF5000',
    fontSize:12,
  },
  itemTitle:{
    marginTop:5,
    letterSpacing:1,
    lineHeight:19,
    marginBottom:3,
  },
  floatButton:{
    position:'absolute',
    justifyContent:'center',
    alignItems:'center',
    width:35,
    height:35,
    zIndex: 99,
  }
})

export const LayoutComponent = IndexScene

export function mapStateToProps(state, props) {
    return {
      routes: state.routes,
      goodsCate: state.goodsCateReducer,
      goodsCateTop: state.goodsCateTopReducer,
      goodsList: state.goodsListIndexReducer,
      goodsKey: state.goodsKeyReducer,
      activityList: state.activityListReducer,
      systemList: state.systemListReducer
    }
}